package com.qf.strategy.service.Impl;

import com.qf.strategy.feign.CacheService;
import com.qf.strategy.service.FilterChain;
import com.qianfeng.smsplatform.common.constants.CacheConstants;
import com.qianfeng.smsplatform.common.model.Standard_Submit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.zip.DataFormatException;

/**
 * @author 徐老板
 * @date 2020/2/27   17:49
 */
@Service
public class SmsFeeFilter implements FilterChain {
    private static final Logger LOGGER = LoggerFactory.getLogger(SmsFeeFilter.class);
    @Resource
    CacheService cacheService;

    @Override
    public boolean dealSms(Standard_Submit submit) throws DataFormatException {
        LOGGER.error("SmsFeeFilter方法执行了:{}",submit);
        //首先获取用户还剩多少钱
        //String fee = cacheService.get(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE + submit.getClientID());
        Object fee = cacheService.getObject(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE + submit.getClientID());
        LOGGER.error("用户当前剩余:{}", fee);
        if (fee==null) {
            //TODO 从数据库中获取然后保存到 redis
        }else{
            int feeint = (int) fee;//转成数字
            Map routerMap = cacheService.hmget(CacheConstants.CACHE_PREFIX_ROUTER + submit.getClientID());
            if (routerMap == null) {
                //TODO 根据防穿透原则去检查数据源

            }else{
                Integer price = (Integer) routerMap.get("price");//获取每一条短信的价格
                //判断
                if (feeint >= price) {
                    //扣费并放行,后面需要注意,如果移动的网关告诉我们短信发送失败的话,我们还需要把用户的钱加回来,所以我们需要保存扣费记录
                    cacheService.decr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE + submit.getClientID(), price);
                    //放行
                    LOGGER.error("发送完成后还剩余:{}",feeint-price);
                    return true;
                }
            }
        }

        //判断每条短信需要多少钱


        return false;

    }
}
